package com.controller.admin;

import com.domain.Link;
import com.domain.PageBean;
import com.service.LinkService;
import com.util.ResponseUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/admin/link")
public class LinkAdminController {
    @Resource
    private LinkService linkService;
    @RequestMapping("/list.do")
    public String list(@RequestParam(value = "page",required = false)String page, @RequestParam(value = "rows",required = false)String rows, HttpServletResponse response) throws IOException {
        PageBean pageBean=new PageBean(Integer.parseInt(page),Integer.parseInt(rows));
        Map<String,Object> map=new HashMap<>();
        map.put("start",pageBean.getStart());
        map.put("size",pageBean.getPageSize());
        List<Link> linkList=linkService.list(map);
        Long total=linkService.getTotal(map);
        JSONObject result=new JSONObject();
        JSONArray jsonArray=JSONArray.fromObject(linkList);
        result.put("rows",jsonArray);
        result.put("total",total);
        ResponseUtil.write(response,result);
        return null;
    }
    @RequestMapping("/delete.do")
    public String delete(@RequestParam("ids")String ids,HttpServletResponse response) throws IOException {
        String[] idsStr=ids.split(",");
        for (int i = 0; i < idsStr.length; i++) {
            linkService.delete(Integer.parseInt(idsStr[i]));
        }
        JSONObject result=new JSONObject();
        result.put("success",Boolean.TRUE);
        ResponseUtil.write(response,result);
        return null;
    }
    @RequestMapping("/save.do")
    public String save(Link link,HttpServletResponse response) throws IOException {
        Integer total=0;
        if(link.getId()!=null){
            total=  linkService.update(link);
        }else {
            total=linkService.add(link);
        }
        JSONObject res=new JSONObject();
        if(total>0){
            res.put("success",Boolean.TRUE);
        }else {
            res.put("success",Boolean.FALSE);
        }
        ResponseUtil.write(response,res);
        return null;
    }
}
